from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse,JsonResponse
from django.shortcuts import render
import os
import parsel,requests,json,datetime

def json(request):
    url = "https://it.ithome.com/"
    headers = {
        "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0'
    }
    response = requests.get(url=url,headers=headers)
    # print(response.text)

    selector = parsel.Selector(response.text)       #使用parsel包中的selector方法，将请求出来的文本进行初始格式化
    all = selector.css('ul.bl')                     #利用css的选择器，定位到该系列标签下

    list1 = []                              #声明一个空列表

    for i in range(10):
        dict1 = {}

        #定位到对应标签下，获取对应属性的值
        title = all.css('.img img ::attr(alt)').getall()
        content = all.css('div.c div.m ::text').getall()
        url = all.css('ul.bl a.img ::attr(href)').getall()
        img = all.css('.img img ::attr(data-original)').getall()

        #将获取到的值，以字典的形式，一一对应，写入dict1字典中
        dict1["标题"] = title[i]
        dict1["内容"] = content[i]
        dict1["url"] = url[i]
        dict1["img"] = img[i]

        list1.append(dict1)

        # list1.append({i: dict1})
    # result = "{" + ", ".join(json.dumps(item, ensure_ascii=False, indent=4)[1:-1] for item in list1) + "}"
    # print(list1)
    return render(request,'news.html',{'list1': list1})
    # return HttpResponse(list1)